<template>
  <el-drawer title="导出数据" v-model="dialogVisible" size="40%">
    <el-form :model="form" label-width="80px">
      <el-form-item label="时间范围">
        <el-date-picker v-model="form.time" clearable type="daterange" range-separator="至" start-placeholder="开始日期" 
        :default-value="[dayjs().subtract(1, 'month'), new dayjs()]"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading">导出</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup>
import { ref, reactive } from "vue"
import { toast } from "~/composables/util";
import { dayjs } from "element-plus";
import { exportNow } from "../../api/exports";
import { ElMessage, ElMessageBox } from 'element-plus'

defineProps({
  tabs: Array
})
const dialogVisible = ref(false)
const loading = ref(false)
const open = () => dialogVisible.value = true
const close = () => dialogVisible.value = false
const today = dayjs().startOf();
const form = reactive({
  tab: null,
  time: [null, null]
})
const checkTwice = async () => {
  try {
    await ElMessageBox.confirm(
      '注意:你确认使用空值导出吗?\n这样可能会导出大量的数据!',
      {
        title: '空值警告',
        confirmButtonText: '确认继续',
        cancelButtonText: '取消导出',
        type: 'warning',
      }
    )
    ElMessage({
      type: 'success',
      message: '确认导出',
    })
    return true
  } catch {
    ElMessage({
      type: 'info',
      message: '导出被取消',
    })
    return false
  }
}
// const checkTwiceAwnser = () => checkTwice().then(result => console.log('then', result)).catch(error => console.log('err', error));
const onSubmit = () => {
  loading.value = true
  // if (form.time && Array.isArray(form.time)) {
  console.log('form',form)
  let dates = {
    begin: form.time[0],
    end: form.time[1]
  }
  // }
  if (!(dates.begin && dates.end)) {// 如果空
    console.log('check2')
    checkTwice().then(res => {
      if (!res) {
        loading.value = false
        close()
        throw "back"
      }
    }).then(() => {
      exportNow(dates).then(data => {
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement("a")
        link.style.display = "none"
        link.href = url
        let filename = `1970-01-01~${dayjs().format('YYYY-MM-DD')}.xls`
        link.setAttribute("download", filename)
        document.body.appendChild(link)
        link.click()
        close()
        toast(`成功导出 1970-01-01 ~ ${dayjs().format('YYYY-MM-DD')} 的数据`)
      }).catch(err => {
        loading.value = false
        toast("导出失败!", err)
      })
    }).catch(err=> {
        console.error('取消导出')
      })
    
  } else {
    if (today.isBefore(dates.begin)) {
      console.log('判断')
      toast("开始日期不能大于在今天之后")
      loading.value = false
      close()
      return
    }
    console.log('here', dates.begin, dates.end, today.isAfter(dates.begin))
    // 如果在结束日期在今天之后
    if (today.isBefore(dates.end)) {
      dates.end = today.format("YYYY-MM-DD")
    }
    exportNow(dates).then(data => {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement("a")
      link.style.display = "none"
      link.href = url
      let filename = `${dates.begin} ~ ${dates.end}.xls`
      link.setAttribute("download", filename)
      document.body.appendChild(link)
      link.click()
      toast(`成功导出 ${dates.begin}~${dates.end} 的数据`)
    }).catch(err => {
      loading.value = false
      toast("导出失败!", err)
    }).finally(() => {
      loading.value = false
      close()
    })
  }
}

defineExpose({
  open
})
</script>